<?php

/**
 * static functions lybrary
 *
 * @author merabi
 */
class fn {

    static function arrayDuplicates($array){
        return array_unique(array_diff_assoc($array, array_unique($array)));
    }

    static function getUrlData($url, $post = null){
        timedebug($url);
        $curl = curl_init($url);
        $filename = "_logs/_curl_." . date_create_from_format('U.u', microtime(true))->format('Y-m-d-H-i-s-u') . ".data.log";

        file_put_contents($filename, $url . ($post ? PHP_EOL . json_encode($post) : "") . PHP_EOL, FILE_APPEND);

        //$fp = fopen("_logs/_curl_." . date_create_from_format('U.u', microtime(true))->format('Y-m-d-H-i-s-u') . ".error.log", "w");
        //curl_setopt($curl, CURLOPT_STDERR, $fp);
        curl_setopt($curl, CURLOPT_COOKIEJAR, "COOKIEJAR.txt");
        curl_setopt($curl, CURLOPT_COOKIEFILE, "COOKIEJAR.txt");
        curl_setopt($curl, CURLOPT_FAILONERROR, true);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_TIMEOUT, 20);

        $header = [];
        $header[] = "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31";
        $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3";
        $header[] = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
        $header[] = "Cache-Control: max-age=0";

        if($post){
            curl_setopt($curl, CURLOPT_POST, 1);
            if(is_array($post))
                curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));
            else
                curl_setopt($curl, CURLOPT_POSTFIELDS, (string) $post);
            $header[] = 'Enctype: application/x-www-form-urlencoded';
        }
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);

        $result = curl_exec($curl);
        $HTTP_CODE = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        file_put_contents($filename, $HTTP_CODE . PHP_EOL . $result . PHP_EOL, FILE_APPEND);
        timedebug($url);
        return $result;
        //return ["data" => $result, "header" => $HTTP_CODE];
    }

    static function get_html_options($param, $data, $selectedID = NULL){

        $options = '';
        foreach($data as $value){
            if($selectedID !== NULL){
                if($selectedID == $value[$param[0]])
                    $selected = 'selected';
                else
                    $selected = '';
            }else{
                $selected = '';
            }
            $options .= "<option {$selected} value=\"{$value[$param[0]]}\">{$value[$param[1]]}</option>\r\n";
        }
        return $options;
    }

}

?>
